/**
 * @description 清单管理Vuex模块
 * @author AI Assistant
 * @date 2023-10-28
 */

import { List } from '@/models/list';
import { Group } from '@/models/group';

// 存储key常量
const STORAGE_KEY = 'ticktock_lists';

// 从本地存储加载清单数据
const loadListsFromStorage = () => {
  try {
    const data = uni.getStorageSync(STORAGE_KEY);
    if (data) {
      // 将普通对象转换为List和Group实例
      const parsedLists = JSON.parse(data).map(listData => {
        const list = new List({
          ...listData,
          groups: listData.groups ? listData.groups.map(groupData => new Group(groupData)) : []
        });
        return list;
      });
      console.log('从本地存储加载清单数据:', parsedLists.length);
      return parsedLists;
    }
  } catch (error) {
    console.error('从本地存储加载清单数据失败:', error);
  }
  return null;
}

// 保存清单数据到本地存储
const saveListsToStorage = (lists) => {
  try {
    const data = JSON.stringify(lists);
    uni.setStorageSync(STORAGE_KEY, data);
    console.log('保存清单数据到本地存储:', lists.length);
  } catch (error) {
    console.error('保存清单数据到本地存储失败:', error);
  }
}

const state = {
  lists: [],
  currentListId: '',
  currentGroupId: ''
};

const getters = {
  getLists: state => state.lists,
  
  getCurrentList: state => {
    return state.lists.find(list => list.id === state.currentListId) || null;
  },
  
  getCurrentGroup: (state, getters) => {
    const currentList = getters.getCurrentList;
    if (!currentList || !currentList.groups) return null;
    
    return currentList.groups.find(group => group.id === state.currentGroupId) || null;
  },
  
  // 获取清单完成情况统计
  getListStats: state => {
    return state.lists.map(list => {
      let totalTasks = 0;
      let completedTasks = 0;
      
      if (list.groups && list.groups.length) {
        list.groups.forEach(group => {
          if (group.tasks && group.tasks.length) {
            totalTasks += group.tasks.length;
            completedTasks += group.tasks.filter(task => task.status === 'done').length;
          }
        });
      }
      
      return {
        id: list.id,
        title: list.title,
        icon: list.icon,
        totalTasks,
        completedTasks
      };
    });
  }
};

const mutations = {
  SET_LISTS(state, lists) {
    console.log('【Vuex】设置清单列表:', lists.length);
    state.lists = lists;
    // 保存到本地存储
    saveListsToStorage(lists);
  },
  
  ADD_LIST(state, list) {
    console.log('【Vuex】添加清单:', list.title);
    state.lists.push(list);
    // 保存到本地存储
    saveListsToStorage(state.lists);
  },
  
  UPDATE_LIST(state, updatedList) {
    console.log('【Vuex】更新清单:', updatedList.title);
    const index = state.lists.findIndex(list => list.id === updatedList.id);
    if (index !== -1) {
      state.lists.splice(index, 1, updatedList);
      console.log('【Vuex】清单更新成功');
      // 保存到本地存储
      saveListsToStorage(state.lists);
    } else {
      console.log('【Vuex】清单更新失败: 未找到对应ID的清单');
    }
  },
  
  DELETE_LIST(state, listId) {
    try {
      console.log('【Vuex】删除清单:', listId);
      
      // 检查listId是否有效
      if (!listId) {
        console.error('【Vuex】删除清单失败: 无效的清单ID');
        return;
      }
      
      // 判断是否删除的是当前选中的清单
      const isCurrentList = state.currentListId === listId;
      
      // 检查清单是否存在
      const listIndex = state.lists.findIndex(list => list.id === listId);
      if (listIndex === -1) {
        console.error('【Vuex】删除清单失败: 未找到清单');
        return;
      }
      
      // 如果要删除的是当前选中清单，先找到一个可选的替代清单
      let nextListId = '';
      if (isCurrentList) {
        // 尝试选择下一个清单，如果没有下一个，则选择上一个
        if (listIndex < state.lists.length - 1) {
          nextListId = state.lists[listIndex + 1].id;
        } else if (listIndex > 0) {
          nextListId = state.lists[listIndex - 1].id;
        }
      }
      
      // 删除清单
      state.lists = state.lists.filter(list => list.id !== listId);
      
      // 更新当前选中状态
      if (isCurrentList) {
        state.currentListId = nextListId || (state.lists.length > 0 ? state.lists[0].id : '');
        state.currentGroupId = '';
        console.log('【Vuex】重置当前选中:', { 
          listId: state.currentListId, 
          groupId: state.currentGroupId 
        });
      }
      
      // 保存到本地存储
      saveListsToStorage(state.lists);
    } catch (error) {
      console.error('【Vuex】删除清单失败:', error);
    }
  },
  
  SET_CURRENT_LIST(state, listId) {
    console.log('【Vuex】设置当前清单:', listId);
    state.currentListId = listId;
    // 当切换清单时，重置当前分组
    state.currentGroupId = '';
  },
  
  SET_CURRENT_GROUP(state, groupId) {
    console.log('【Vuex】设置当前分组:', groupId);
    state.currentGroupId = groupId;
  },
  
  ADD_GROUP(state, { listId, group }) {
    const list = state.lists.find(list => list.id === listId);
    if (list) {
      if (!list.groups) list.groups = [];
      list.groups.push(group);
      // 保存到本地存储
      saveListsToStorage(state.lists);
    }
  },
  
  UPDATE_GROUP(state, { listId, group }) {
    const list = state.lists.find(list => list.id === listId);
    if (list && list.groups) {
      const index = list.groups.findIndex(g => g.id === group.id);
      if (index !== -1) {
        list.groups.splice(index, 1, group);
        // 保存到本地存储
        saveListsToStorage(state.lists);
      }
    }
  },
  
  DELETE_GROUP(state, { listId, groupId }) {
    const list = state.lists.find(list => list.id === listId);
    if (list && list.groups) {
      list.groups = list.groups.filter(group => group.id !== groupId);
      if (state.currentGroupId === groupId) {
        state.currentGroupId = list.groups.length > 0 ? list.groups[0].id : '';
      }
      // 保存到本地存储
      saveListsToStorage(state.lists);
    }
  }
};

const actions = {
  // 初始化清单数据
  async initLists({ commit }) {
    try {
      // 先尝试从本地存储加载数据
      const storedLists = loadListsFromStorage();
      
      if (storedLists && storedLists.length > 0) {
        // 如果本地存储有数据，使用本地数据
        commit('SET_LISTS', storedLists);
      } else {
        // 如果本地存储没有数据，使用默认数据
        const mockLists = [
          new List({
            id: 'list1',
            title: '工作清单',
            icon: 'file-text',
            groups: [
              new Group({
                id: 'group1',
                name: '项目A',
                listId: 'list1',
                tasks: []
              }),
              new Group({
                id: 'group2',
                name: '项目B',
                listId: 'list1',
                tasks: []
              })
            ]
          }),
          new List({
            id: 'list2',
            title: '学习清单',
            icon: 'bookmark',
            groups: [
              new Group({
                id: 'group3',
                name: '前端课程',
                listId: 'list2',
                tasks: []
              }),
              new Group({
                id: 'group4',
                name: '后端课程',
                listId: 'list2',
                tasks: []
              })
            ]
          }),
          new List({
            id: 'list3',
            title: '个人清单',
            icon: 'account',
            groups: [
              new Group({
                id: 'group5',
                name: '日常任务',
                listId: 'list3',
                tasks: []
              })
            ]
          })
        ];
        
        commit('SET_LISTS', mockLists);
      }
      
      // 设置默认选中的清单和分组
      const lists = loadListsFromStorage() || [];
      if (lists.length > 0) {
        commit('SET_CURRENT_LIST', lists[0].id);
        if (lists[0].groups && lists[0].groups.length > 0) {
          commit('SET_CURRENT_GROUP', lists[0].groups[0].id);
        }
      }
    } catch (error) {
      console.error('初始化清单数据失败', error);
    }
  },
  
  // 创建新清单
  createList({ commit }, listData) {
    const newList = new List({
      ...listData,
      id: 'list_' + Date.now(), // 简单的ID生成
      createTime: Date.now(),
      updateTime: Date.now()
    });
    
    commit('ADD_LIST', newList);
    return newList;
  },
  
  // 更新清单
  updateList({ commit }, listData) {
    const updatedList = new List({
      ...listData,
      updateTime: Date.now()
    });
    
    commit('UPDATE_LIST', updatedList);
    return updatedList;
  },
  
  // 删除清单
  deleteList({ commit }, listId) {
    commit('DELETE_LIST', listId);
  },
  
  // 设置当前清单
  setCurrentList({ commit }, listId) {
    commit('SET_CURRENT_LIST', listId);
  },
  
  // 设置当前分组
  setCurrentGroup({ commit }, groupId) {
    commit('SET_CURRENT_GROUP', groupId);
  },
  
  // 创建新分组
  createGroup({ commit }, { listId, groupData }) {
    const newGroup = new Group({
      ...groupData,
      id: 'group_' + Date.now(), // 简单的ID生成
      listId,
      createTime: Date.now(),
      updateTime: Date.now()
    });
    
    commit('ADD_GROUP', { listId, group: newGroup });
    return newGroup;
  },
  
  // 更新分组
  updateGroup({ commit }, { listId, groupData }) {
    const updatedGroup = new Group({
      ...groupData,
      updateTime: Date.now()
    });
    
    commit('UPDATE_GROUP', { listId, group: updatedGroup });
    return updatedGroup;
  },
  
  // 删除分组
  deleteGroup({ commit }, { listId, groupId }) {
    commit('DELETE_GROUP', { listId, groupId });
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}; 